package com.wt.easyadmin.common.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wt.easyadmin.common.Constants;
import com.wt.easyadmin.common.annotation.JwtToken;
import com.wt.easyadmin.common.utils.JsonUtil;
import com.wt.easyadmin.common.utils.JwtUtil;

public class JwtInterceptor implements HandlerInterceptor {
	
	private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader(Constants.JWT_TOKEN_KEY);
        httpServletResponse.setHeader(Constants.JWT_TOKEN_KEY, token);
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(JwtToken.class)) {
            JwtToken jwtToken = method.getAnnotation(JwtToken.class);
            if (jwtToken.required()) {
                log.info("jwt1:=="+JsonUtil.getInstance().obj2json(token));
            	
                // 执行认证
                if (StringUtils.isEmpty(jwtToken)) {
                    throw new UnauthorizedException("无token，请重新登录");
                }
                // 获取 token 中的 userId
                String userId = JwtUtil.getUserId(token);
                log.info("用户id:========" + userId);
                // 验证 token
                if(!JwtUtil.checkSign(token)) {  
                	log.info("刷新token");
                    httpServletResponse.setHeader(Constants.JWT_TOKEN_KEY, JwtUtil.sign(userId));

                };
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}